<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="售后人员姓名" prop="name">
            <el-input
              v-model="baTable.form.items!.name"
              placeholder="请输入售后人员姓名"
            />
            <div class="block-help">同名用户后添加数字，如01 加以区分</div>
          </el-form-item>
          <el-form-item label="售后人员电话" prop="phone">
            <el-input
              v-model="baTable.form.items!.phone"
              placeholder="请输入售后人员电话"
              maxlength="11"
            />
          </el-form-item>
          <!-- <el-form-item label="隶属服务商" prop="providerId">
              <el-input
                v-model="baTable.form.items!.providerId"
                placeholder="请选择隶属服务商"
                disabled
              />
            </el-form-item> -->
          <el-form-item label="身份证正反照">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :headers="headerConfig"
              list-type="picture-card"
              name="idPhoto"
              :on-change="changUpload"
              :on-remove="handleRemove"
              :auto-upload="false"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="资格证">
            <el-upload
              ref="uploadPhotoRef"
              :limit="1"
              :headers="headerConfig"
              list-type="picture-card"
              v-model:file-list="certificateFileList"
              :auto-upload="false"
              :on-change="changUploadCert"
              :on-remove="handleRemoveCert"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="个人登记照片">
            <el-upload
              ref="uploadPhotoRef"
              :limit="1"
              list-type="picture-card"
              v-model:file-list="photoFileList"
              :auto-upload="false"
              :on-change="changUploadPhoto"
              :on-remove="handleRemovePhoto"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item label="工时" prop="workHours">
                <el-input-number
                  v-model="baTable.form.items!.workHours"
                  controls-position="right"
                  :min="0"
                />
              </el-form-item> -->
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted } from "vue";
import type baTableClass from "@/utils/baTable";
import { _upload } from "@/utils/axios";
import { ElNotification } from "element-plus"; //处理导航信息
import type {
  UploadProps,
  UploadUserFile,
  UploadInstance,
  UploadRequestOptions,
  ElForm,
  FormRules,
  ElTree,
  UploadFile,
  UploadFiles,
} from "element-plus";

//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
// const service = inject("service") as any;
const adminInfo = inject("adminInfo") as any;
const formRef = ref<InstanceType<typeof ElForm>>();
const uploadRef = ref<UploadInstance>();
const uploadPhotoRef = ref<UploadInstance>();

// 身份证照片
const fileList = ref<UploadUserFile[]>([]);
const realUploadFile = ref<UploadUserFile[]>([]);
// 资质照
const certificateFileList = ref<UploadUserFile[]>([]);
const certificateUploadFile = ref<UploadUserFile[]>([]);
//个人登记照片
const photoFileList = ref<UploadUserFile[]>([]);
const photoRealUploadFile = ref<UploadUserFile[]>([]);

const headerConfig = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};

type Option = {
  id: number;
  label: string;
  children: Option[];
};
const state: {
  deptOptions: Option[];
  host: string;
} = reactive({
  host: "",
  deptOptions: [], //部门列表
});
const rules = reactive<FormRules>({
  name: [{ required: true, message: "售后人员姓名不能为空", trigger: "blur" }],
  phone: [
    {
      required: true,
      message: "售后人员电话",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
    // { type: "string", message: "长度不能超过30位", trigger: "blur", max: 30 },
  ],
  providerId: [
    { required: true, message: "隶属服务商不能为空", trigger: "blur" },
  ],
});

//移除身份证照片
const handleRemove: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = fileList.value.filter((item) => {
    return item.uid != uid;
  });
  fileList.value = selectFileList;
};

//身份证照片文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUpload: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles, uploadFiles[0].raw);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.png|.jpg|.jpeg$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.png|.jpg|.jpeg",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //将上传的设备图片信息存入列表
  fileList.value.push(uploadFile);
  realUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFile.raw as any); //添加文件对象
  formData.append("name", "pic");
  _upload("/common/upload", formData, "").then((res: any) => {
    if (fileList.value.length > 1) {
      baTable.form.items!.idPhotoBack =
        state.host === "" ? res.data.url : state.host + res.data.fileName;
    } else {
      baTable.form.items!.idPhoto =
        state.host === "" ? res.data.url : state.host + res.data.fileName;
    }
    console.log("身份证照片", fileList.value, baTable.form.items);

    // baTable.form.items!.idPhoto =
    //   "http://47.103.39.74:8088" + res.data.fileName;
  });
};

// 个人登记照片移除
const handleRemovePhoto: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = photoFileList.value.filter((item) => {
    return item.uid != uid;
  });
  photoFileList.value = selectFileList;
};
const changUploadPhoto: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = photoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    photoFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = photoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    photoFileList.value = selectFileList;
    return;
  }
  // 将个人登记照片存入列表
  photoFileList.value.push(uploadFile);
  photoRealUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFile.raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    baTable.form.items!.photo =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    console.log("个人登记照片", baTable.form.items);
    // baTable.form.items!.businessLicense =
    //   "http://47.103.39.74:8088" + res.data.fileName;
    // baTable.form.items!.businessLicense = res.data.originalFilename;
  });
};

//移除资格证书
const handleRemoveCert: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = certificateFileList.value.filter((item) => {
    return item.uid != uid;
  });
  certificateFileList.value = selectFileList;
};
//资格证书状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadCert: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = certificateFileList.value.filter((item) => {
      return item.uid != uid;
    });
    certificateFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = certificateFileList.value.filter((item) => {
      return item.uid != uid;
    });
    certificateFileList.value = selectFileList;
    return;
  }
  // 将资格证书文件信息存入列表
  certificateFileList.value.push(uploadFile);

  certificateUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFile.raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    baTable.form.items!.qualification =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
  });
};

onMounted(() => {
  console.log("baTable.form.operate", baTable.form.operate);
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
</style>
